package cn.tedu.serviceEdu.controller;


import cn.tedu.commonUtils.JwtUtils;
import cn.tedu.commonUtils.R;
import cn.tedu.serviceEdu.client.UcenterClient;
import cn.tedu.serviceEdu.entity.EduComment;
import cn.tedu.serviceEdu.service.EduCourseService;
import cn.tedu.serviceEdu.service.IEduCommentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-05-25
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/eduservice/comment")
public class EduCommentController {
    @Autowired
    private IEduCommentService commentService;

    @Autowired
    private UcenterClient ucenterClient;

    @GetMapping("/{current}/{pageSize}")
    public R page(@PathVariable Long current,@PathVariable Long pageSize,String courseId){
        Page<EduComment> pageInfo = new Page<>(current,pageSize);
        LambdaQueryWrapper<EduComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!courseId.isEmpty(),EduComment::getCourseId,courseId);
        commentService.page(pageInfo,wrapper);
        HashMap<String, Object> map = new HashMap<>();
        List<EduComment> commentList = pageInfo.getRecords();
        map.put("items", commentList);
        map.put("current", pageInfo.getCurrent());
        map.put("pages", pageInfo.getPages());
        map.put("size", pageInfo.getSize());
        map.put("total", pageInfo.getTotal());
        map.put("hasNext", pageInfo.hasNext());
        map.put("hasPrevious", pageInfo.hasPrevious());
        return R.ok().data(map);
    }
    @PostMapping("/save")
    public R save(@RequestBody EduComment comment, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(memberId.isEmpty()){
            return R.error().msg("请先等录");
        }
        Map<String,Object> map = ucenterClient.getMemberById(memberId);
        String nickName = (String) map.get("nickName");
        String avatar = (String) map.get("avatar");
        comment.setMemberId(memberId);
        comment.setNickname(nickName);
        comment.setAvatar(avatar);
        commentService.save(comment);
        return R.ok();
    }
}

